<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>动画</title>
</head>
<style>
    button {
        width: 100px;
        height: 40px;
        line-height: 40px;
        border-radius: 10px;
        font-size: 20px;
        border: none;
        background-image: linear-gradient(#f9bccc, #d7b3e3, #bdb6ec);
    }

    div {
        margin-top: 20px;
        width: 100px;
        height: 100px;
        border-radius: 100px;
        position: relative;
    }

    .A {
        position: absolute;
        left: 0;
        top: 40px;
        background-color: #bdb6ec;
    }

    .B {
        position: absolute;
        left: 1000px;
        top: 160px;
        background-color: #f9bccc;
    }
</style>

<body>
    <button class="R">向右滚动</button>
    <button class="L">向左滚动</button>
    <button class="ST">停止</button>
    <div class="A"></div>
    <div class="B"></div>
</body>
<script>
    var R = document.querySelector('.R')
    var L = document.querySelector('.L')
    var ST = document.querySelector('.ST')
    var A = document.querySelector('.A')
    var B = document.querySelector('.B')

    R.onclick = function () {

        getSpeed(A, 1000, 8, 10, function () {
            getSpeed(A, 0, 8, 10)
        })

    }
    L.onclick = function () {
        getSpeed(B, 0, 8, 10, function () {
            getSpeed(B, 1000, 8, 10)
        })
    }
    ST.onclick = function () {
        clearInterval(A.timer)
        clearInterval(B.timer)
    }

    function getSpeed(obj, target, speed, time, fn) {

        clearInterval(obj.timer)
        var s = obj.offsetLeft;
        // 判定 目标移动 正负
        speed = target - s > 0 ? speed : -speed;

        obj.timer = setInterval(function (e) {

            s = obj.offsetLeft;

            // 判断 目标 停止的位置
            if (s == target) {
                s = target;
                clearInterval(obj.timer);
                // 启用 回调函数
                fn && fn();
            } else {
                // 目标移动位置
                obj.style.left = s + speed + 'px'
                // console.log(obj.style.left);
            }
        }, time)
    }
</script>

</html>